package com.spring.jiminshiro.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2018/3/27
 */
public class UrlAuthorizationFilter extends AuthorizationFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * Returns <code>true</code> if the request is allowed to proceed through the filter normally, or <code>false</code>
     * if the request should be handled by the
     * {@link #onAccessDenied(ServletRequest, ServletResponse, Object) onAccessDenied(request,response,mappedValue)}
     * method instead.
     *
     * @param request     the incoming <code>ServletRequest</code>
     * @param response    the outgoing <code>ServletResponse</code>
     * @param mappedValue the filter-specific config value mapped to this filter in the URL rules mappings.
     * @return <code>true</code> if the request should proceed through the filter normally, <code>false</code> if the
     * request should be processed by this filter's
     * {@link #onAccessDenied(ServletRequest, ServletResponse, Object)} method instead.
     * @throws Exception if an error occurs during processing.
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        logger.info("RequestURL:{}", httpServletRequest.getRequestURL().toString());
        logger.info("RequestURI:{}",httpServletRequest.getRequestURI());
        logger.info("ContextPath:{}",httpServletRequest.getContextPath());
        logger.info("ServletPath:{}",httpServletRequest.getServletPath());
        logger.info("Method:{}",httpServletRequest.getMethod());
        Subject currentUser = this.getSubject(request, response);
        if (currentUser.isAuthenticated()) {
            logger.info("当前用户已登录");
        } else {
            logger.info("当前用户未登录");
        }
        Object object = currentUser.getPrincipal();
        if (object == null) {
            return false;
        }
        logger.info(object.toString());
        if (!antPathMatcher.match("/test", httpServletRequest.getRequestURI())) {
            return false;
        }
        return true;
    }
}
